import 'dart:convert';

import 'package:app_flutter/beans/bussdetail_bean.dart';
import 'package:app_flutter/view/loading.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

import '../const.dart';

class DetailPage extends StatefulWidget {
  final inscode;

  const DetailPage({Key key, this.inscode}) : super(key: key);

  @override
  _DetailPageState createState() => _DetailPageState();
}

class _DetailPageState extends State<DetailPage> {
  var loadingDialog;
  var titles1 = const [
    '行政区域',
    '培训机构编号',
    '驾培机构名称',
    '经营许可编号',
    '联系人',
    '联系电话',
    '经营许可日期',
    '法人代表',
    '培训机构简称',
    '营业执照注册号',
    '统一社会信息代码',
    '邮政编码',
    '经营范围',
    '经营状态',
    '创建时间',
    '更新时间',
    '培训机构地址',
  ];
  var titles2 = const [
    '分类等级',
    '教练车总数',
    '教练员总数',
    '考核员数',
    '教室总面积(平方米)',
    '安全管理人数',
    '理论教室面积(平方米)',
    '教练长总面积(平方米)',
  ];
  var content1 = List();
  var content2 = List();
  GlobalKey _tabBarKey = new GlobalKey();

  List<Widget> _sliverBuilder(BuildContext context, bool innerBoxIsScrolled) {
    return <Widget>[
      SliverAppBar(
        backgroundColor: Color(0xff23AFDC),
        title: Text('信息详情'),
        centerTitle: true,
        //标题居中
        // expandedHeight: 200.0,  //展开高度200
        floating: false,
        //不随着滑动隐藏标题
        pinned: false, //固定在顶部
      )
    ];
  }

  _getSize() {
    RenderObject renderObject = _tabBarKey.currentContext.findRenderObject();
    print(
        "semanticBounds:${renderObject.semanticBounds.size} paintBounds:${renderObject.paintBounds.size} size:${_tabBarKey.currentContext.size}");
    return _tabBarKey.currentContext.size.height;
  }

  _showDialog() {
    loadingDialog = LoadingDialog(
      text: '加载中...',
    );
    showDialog<Null>(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return loadingDialog;
        });
  }

  Future<Null> _getByInscode() async {
    Map data = Map<String, dynamic>();
    data["inscode"] = widget.inscode;
    print('_getByInscode_inscode:${widget.inscode}');
    try {
      Dio dio = Dio(Const.get);
      print(dio.options.method);
      Response response =
          await dio.request('/api/bussSch/getByInscode', queryParameters: data);

      if (loadingDialog != null) {
        loadingDialog = null;
        Navigator.pop(context);
      }

      Map<String, dynamic> decoded = json.decode(response.toString());
      print('response:$response');
      BussdetailBean bussdetailBean = BussdetailBean.fromJson(decoded);
      setState(() {});
    } catch (e) {
      print(e);
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getByInscode();
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> tabs = [
      renderTab(Text('企业基本信息')),
      renderTab(Text("企业经营信息")),
    ];
    return Scaffold(
        body: NestedScrollView(
            headerSliverBuilder: _sliverBuilder,
            body: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    '定兴县兴钥家是永远培训有限公司',
                    style: TextStyle(
                        fontSize: 16.0, color: const Color(0xff333333)),
                  ),
                  SizedBox(
                    height: 20,
                  ),
                  GestureDetector(
                    onTap: () {
                      _getSize();
                    },
                    child: Row(
                      children: <Widget>[
                        Image.asset(
                          'images/icon_dshyz.png',
                          height: 100,
                          width: 100,
                          fit: BoxFit.fill,
                        ),
                        Image.asset(
                          'images/icon_jcbayz.png',
                          height: 100,
                          width: 100,
                          fit: BoxFit.fill,
                        ),
                      ],
                    ),
                  ),
                  Expanded(
                    key: _tabBarKey,
                    child: TabBarWidget(
                      initPage: 0,
                      hostTitle: '111',
                      tabItems: tabs,
                      tabViews: [
                        Page(titles: titles1, content: content1),
                        Page(titles: titles2, content: content2)
                      ],
                      indicatorColor: Color(0xff23AFDC),
                    ),
                  ),
                ],
              ),
            )));
  }

  renderTab(text) {
    //返回一个标签
    return Tab(
        child: Container(
      //设置paddingTop为6
      padding: EdgeInsets.only(top: 6),
      //一个列控件
      child: Column(
        //竖直方向居中
        mainAxisAlignment: MainAxisAlignment.center,
        //水平方向居中
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[text],
      ),
    ));
  }
}

class TabBarWidget extends StatefulWidget {
  final String hostTitle;
  final List<Widget> tabItems;
  final List<Widget> tabViews;
  final Color backgroundColor;
  final Color indicatorColor;
  final int initPage;
  final ValueChanged<int> onPageChanged;

  TabBarWidget(
      {Key key,
      this.hostTitle,
      this.tabItems,
      this.tabViews,
      this.backgroundColor,
      this.indicatorColor,
      this.initPage,
      this.onPageChanged})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _TabBarState(
        this.tabViews, this.indicatorColor, this.initPage, this.onPageChanged);
  }
}

class _TabBarState extends State<TabBarWidget>
    with SingleTickerProviderStateMixin {
  final int _initPage;
  final List<Widget> _tabViews;
  final Color _indicatorColor;
  final ValueChanged<int> _onPageChanged;

  _TabBarState(
      this._tabViews, this._indicatorColor, this._initPage, this._onPageChanged)
      : super();
  TabController _tabController;
  PageController _pageController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(
        initialIndex: _initPage, length: widget.tabItems.length, vsync: this);
    _pageController = PageController(initialPage: _initPage, keepPage: true);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _tabController.dispose();
    _pageController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        TabBar(
          tabs: widget.tabItems,
          controller: _tabController,
          indicatorColor: _indicatorColor,
          indicatorSize: TabBarIndicatorSize.label,
          labelColor: Color(0xff23AFDC),
          unselectedLabelColor: Color(0xff999999),
          onTap: (index) {
            _pageController.jumpToPage(index);
          },
        ),
        Expanded(
          child: PageView(
            controller: _pageController,
            children: _tabViews,
            onPageChanged: (index) {
              _tabController.animateTo(index);
              _onPageChanged?.call(index);
            },
          ),
        ),
      ],
    );
  }
}

class Page extends StatelessWidget {
  final titles;
  final content;

  const Page({Key key, this.titles, this.content}) : super(key: key);

  _doWidgets(List list) {
    var widgets = List();
    for (String s in titles) {
      widgets.add(Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Text(
            s,
            style: TextStyle(fontSize: 14, color: const Color(0xff333333)),
          ),
          Text(
            s,
            style: TextStyle(fontSize: 14, color: const Color(0xff333333)),
          ),
        ],
      ));
    }
    return widgets;
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 10),
      child: ListView.separated(
        shrinkWrap: true,
        itemBuilder: (context, index) => _doWidgets(titles)[index],
        separatorBuilder: (context, index) => Divider(
          color: Color(0xffF0F0F0),
        ),
        itemCount: _doWidgets(titles).length,
      ),
    );
  }
}
